package service

import (
	"GinBlog/global"
	"GinBlog/models"
	"GinBlog/models/request"
	"errors"
)

type PostService struct{}

func (u *PostService) Create(post *models.Post) {
	global.DB.Create(&post)
}

func (u *PostService) Get(id uint) *models.Post {
	post := &models.Post{}
	global.DB.First(&post, id)
	return post
}

func (u *PostService) Update(post *models.Post, userid uint) error {
	p := u.Get(post.ID)
	if p.ID == 0 {
		return errors.New("文章不存在")
	}
	if *p.UserID != userid {
		return errors.New("没有权限")
	}
	p.Title = post.Title
	p.Content = post.Content
	global.DB.Save(&p)
	return nil
}

func (u *PostService) Delete(id uint, userid uint) error {
	p := u.Get(id)
	if p.ID == 0 {
		return errors.New("文章不存在")
	}
	if *p.UserID != userid {
		return errors.New("没有权限")
	}
	global.DB.Delete(&models.Post{}, id)
	return nil
}

func (u *PostService) List(info request.ListPostRequest) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.DB.Model(&models.Post{})
	var postList []models.Post

	if info.Title != "" {
		db = db.Where("title LIKE ?", "%"+info.Title+"%")
	}
	if info.Content != "" {
		db = db.Where("content LIKE ?", "%"+info.Content+"%")
	}
	if info.UserId != 0 {
		db = db.Where("user_id = ?", info.UserId)
	}

	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Preload("Comments").Preload("User").Find(&postList).Error
	return postList, total, err
}
